class UsersController < ApplicationController
  before_action :set_menu

  def index
    @submenu = :user_list
    @title = '用户管理'
    @users = User.all
    if params.has_key? :delete
      @user = User.find params[:delete]
      @user.destroy
      redirect_to '/users/index'
    end
  end

  def new
    @title = '用户管理/新增'
    @buttons.push :action => '/users/index', :label => "返回"
    @roles = Role.all
    @before_qty = User.all.size
    if params.has_key? :save
      @user = User.create(name: params[:name], email: params[:email], password: params[:password])
      @after_qty = User.all.size
      if @before_qty < @after_qty
        params.each do |k|
          if k[0].split("_")[0] == 'role'
            @key = k[0].split("_")[0]
            @ndx = k[0].split("_")[1]
            @val = k[1]
            @role = Role.find @val
            @user_role_relation = UserRoleRelation.create(user_id: @user.id, role_id: @role.id)
          end
        end
        redirect_to '/users/index'
      else
        @infos.push @user.errors.full_messages
      end
    end
  end

  def edit
    @title = '用户管理/修改'
    @buttons.push :action => '/users/index', :label => "返回"
    @user = User.find params[:id]
    @roles = Role.all
    if params.has_key? :save
      @user.update(name: params[:name], email: params[:email], password: params[:password])
      if @user.errors.full_messages == []
        @user.roles.destroy_all
        params.each do |k|
          if k[0].split("_")[0] == 'role'
            @key = k[0].split("_")[0]
            @ndx = k[0].split("_")[1]
            @val = k[1]
            @role = Role.find @val
            @user_role_relation = UserRoleRelation.create(user_id: @user.id, role_id: @role.id)
          end
        end
        redirect_to '/users/index'
      else
        @infos.push @user.errors.full_messages
      end
    end
  end

  
  private
  def set_menu
    @mainmenu = :people
  end
end
